from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import SportTypes
import uuid
from flask_jwt_extended import jwt_required
from utils.h_result import HResult

bp = Blueprint('sport_types', __name__, url_prefix='/sport-types/')

class AddSportType(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        name = data.get('name')
        
        if not name:
            return HResult().get_result('error', '参数错误!')
            
        sport_type = SportTypes(
            id=str(uuid.uuid4()),
            name=name
        )
        
        if 'description' in data:
            sport_type.description = data['description']
            
        db.session.add(sport_type)
        db.session.commit()
        return HResult().get_result('success', '添加成功!', sport_type.to_dict())

class DeleteSportType(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        type_ids = data['ids']
        
        for type_id in type_ids:
            sport_type = SportTypes.query.filter_by(id=type_id).first()
            if sport_type:
                db.session.delete(sport_type)
                
        db.session.commit()
        return HResult().get_result('success', '删除成功!')

class UpdateSportType(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        type_id = data['id']
        
        sport_type = SportTypes.query.filter_by(id=type_id).first()
        if not sport_type:
            return HResult().get_result('error', '运动类型不存在!')
            
        for key, value in data.items():
            if key != 'id':
                setattr(sport_type, key, value)
                
        db.session.commit()
        return HResult().get_result('success', '修改成功!')

class SportTypeInfo(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        type_id = request.args.get('id')
        sport_type = SportTypes.query.filter_by(id=type_id).first()
        
        if not sport_type:
            return HResult().get_result('error', '运动类型不存在!')
            
        return HResult().get_result('success', data=sport_type.to_dict())

class QueryAllSportTypes(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        sport_types = SportTypes.query.all()
        return HResult().get_result('success', data=[st.to_dict() for st in sport_types])

api = Api(bp)
api.add_resource(AddSportType, '/add/', endpoint='add')
api.add_resource(DeleteSportType, '/delete/', endpoint='delete')
api.add_resource(UpdateSportType, '/update/', endpoint='update')
api.add_resource(SportTypeInfo, '/info/', endpoint='info')
api.add_resource(QueryAllSportTypes, '/list/', endpoint='list') 